#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using Library.Entity;
using Library.Services;
using System.Collections;

#endregion

namespace Library
{
    public partial class FormBookBorrow : Form,  IFindMember, IFormBookBorrowAddBook
    {
        BookTransaction m_BookTransaction;
        User m_currnUser;
        BookTransactionService m_BookTransactionService = new BookTransactionService();
        BookService m_BookService = new BookService();
        MemberService m_MemberService = new MemberService();
        UserControlBookBorrow m_UserControlBookBorrow;
       // Book m_book = null;
        Member m_member = null;
        bool m_apply = false;

        public FormBookBorrow(BookTransaction BookTransaction, User currnBookCategory, UserControlBookBorrow BookCategoryControlBookCategory)
        {
            InitializeComponent();
            labelTitle.Text = "Book Borrow";
            Text = "Book Borrow";
            m_BookTransaction = BookTransaction;
            m_currnUser = currnBookCategory;
            m_UserControlBookBorrow = BookCategoryControlBookCategory;
            initComboBox();
            loadBookCategory();
            initEnterKeyDown(this.Controls);
        }

        private void initComboBox()
        {
        }

        private void initEnterKeyDown(Control.ControlCollection controls)
        {
            foreach (Control c in controls)
            {
                if (c is TextBox)
                {
                    TextBox txtB = (TextBox)c;
                    txtB.EnterKeyDown += new KeyEventHandler(txtB_EnterKeyDown);
                }
                if (c is CheckBox)
                {
                    CheckBox txtB = (CheckBox)c;
                    txtB.KeyDown += new KeyEventHandler(txtB_KeyDown);
                }
                if (c is ComboBox)
                {
                    ComboBox txtB = (ComboBox)c;
                    txtB.KeyDown += new KeyEventHandler(txtB_KeyDown);
                }
                if (c is DateTimePicker)
                {
                    DateTimePicker txtB = (DateTimePicker)c;
                    txtB.KeyDown += new KeyEventHandler(txtB_KeyDown);
                }
                if (c is NumericUpDown)
                {
                    NumericUpDown txtB = (NumericUpDown)c;
                    txtB.KeyDown += new KeyEventHandler(txtB_KeyDown);
                }
                initEnterKeyDown(c.Controls);
            }
        }

        void txtB_KeyDown(object objSender, KeyEventArgs objArgs)
        {
            if (objArgs.KeyCode == Keys.Enter)
            {
                Control ctrl = (Control)objSender;
                SelectNextControl(ctrl, true, true, true, true);
            }
        }

        void txtB_EnterKeyDown(object objSender, KeyEventArgs objArgs)
        {
            Control ctrl = (Control)objSender;
            SelectNextControl(ctrl, true, true, true, true);
        }

        private void loadBookCategory()
        {
            if (m_BookTransaction.Id > 0)
            {
               ///m_book = m_BookService.GetBookById(m_BookBookTransaction.BookId);
               /// textBoxBookCode.Text = m_book.Code;
               // textBoxBookTitle.Text = m_book.Name;
                m_member = m_MemberService.GetMemberById(m_BookTransaction.MemberId);
                textBoxMemberCode.Text = m_member.Code;
                textBoxMemberName.Text = m_member.Name;
            }
            textBoxRemark.Text = m_BookTransaction.Remark;
            dateTimePickerTrDate.Value = m_BookTransaction.TransactionDate;
            dateTimePickerBorrowDate.Value = m_BookTransaction.BorrowDate;
            m_BookTransaction.BorrowList = m_BookTransactionService.GetBookTransactionByBookTransactionCodeList(m_BookTransaction.Code);
            foreach (BookTransaction trBook in m_BookTransaction.BorrowList)
            {
                trBook.Book = m_BookService.GetBookById(trBook.BookId);
                trBook.Book.Tag = trBook.Quantity;
                AddBook(trBook.Book);
            }
           // numericUpQuantity.Value = m_BookBookTransaction.Quantity;
           // buttonFindBook.Visible = m_BookBookTransaction.Id == 0;
           // textBoxBookCode.Enabled = m_BookBookTransaction.Id == 0;
            buttonApply.Visible = m_BookTransaction.Id != 0;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (isValid())
            {
                UpdateEntity();
                try
                {
                    if (m_BookTransaction.Id == 0)
                    {
                        m_BookTransactionService.InsertNewBookTransactionBorrow(m_BookTransaction);
                        foreach (BookTransaction tr in m_BookTransaction.BorrowList)
                        {
                            tr.Code = m_BookTransaction.Code;
                            m_UserControlBookBorrow.AddNewData(tr);
                        }
                    }
                    else
                    {
                        m_BookTransactionService.UpdateBookTransactionBorrow(m_BookTransaction);
                        m_UserControlBookBorrow.UpdateData(m_BookTransaction);
                    }
                    MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, new EventHandler(CloseForm));
                }
                catch (Exception x)
                {
                    MessageBox.Show(x.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }

            }
        }
        void CloseForm(object sender, EventArgs e)
        {
            if (!m_apply)
                Close();
            m_apply = false;
        }

        private void UpdateEntity()
        {
            //m_BookBookTransaction.Name = m_book.Code + " - " + m_book.Name;
            m_BookTransaction.Remark = textBoxRemark.Text;
            m_BookTransaction.CreatedUserId = m_currnUser.Id;
            m_BookTransaction.ModifiedUserId = m_currnUser.Id;
           // m_BookBookTransaction.BookId = m_book.Id;
            m_BookTransaction.TransactionDate = dateTimePickerTrDate.Value;
            m_BookTransaction.BorrowDate = dateTimePickerBorrowDate.Value;
            m_BookTransaction.MemberId = m_member.Id;
            m_BookTransaction.TransactionType = TransactionType.Borrow;

            m_BookTransaction.BorrowList.Clear();
            foreach (ListViewItem itm in listView.Items)
            {
                Book book = (Book)itm.Tag;
                BookTransaction trBook = new BookTransaction();
                trBook.MemberId = m_member.Id;
                trBook.BookId = book.Id;
                trBook.Book = book;
                trBook.TransactionType = TransactionType.Borrow;
                trBook.Remark = m_BookTransaction.Remark;
                trBook.Quantity = Convert.ToDecimal(book.Tag);
                m_BookTransaction.BorrowList.Add(trBook);
            }
           // m_BookBookTransaction.Quantity = numericUpQuantity.Value;
        }

        private bool isValid()
        {
            clearError();
            bool validBookcode = listView.Items.Count > 0;
            bool validMembercode = textBoxMemberName.Text != "";
           // bool validQty = numericUpQuantity.Value != 0;
           // if (validBookcode)
            //{
               // m_book = m_BookService.GetBookByBookCode(textBoxBookCode.Text);
               // validBookcode = m_book != null;
          //  }
            if (validMembercode)
            {
                m_member = m_MemberService.GetMemberByMemberCode(textBoxMemberCode.Text);
                validMembercode = m_member != null;
            }
            if (!validBookcode) errorProvider.SetError(listView, "Fill Book Code / Invalid Book");
            if (!validMembercode) errorProvider.SetError(textBoxMemberCode, "Fill Member Code / Invalid Member");
           // if (!validQty) errorProvider.SetError(numericUpQuantity, "Fill Qty");
            //return validBookcode && validQty && validMembercode;
            return validMembercode && validBookcode;
        }

        private void clearError()
        {
           //errorProvider.SetError(textBoxBookCode, "");
           //errorProvider.SetError(numericUpQuantity, "");
            errorProvider.SetError(textBoxMemberCode, "");
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonApply_Click(object sender, EventArgs e)
        {
            m_apply = true;
            buttonSave_Click(sender, e);
        }

        //private void buttonFindBook_Click(object sender, EventArgs e)
        //{
        //    FormFindBook form = new FormFindBook(this);
        //    form.ShowDialog();
        //}
        //public void SetBook(Book book)
        //{
        //    m_book = book;
        //    textBoxBookTitle.Text = book.Name;
        //    textBoxBookCode.Text = book.Code;
        //    textBoxBookCode.Focus();
        //    textBoxBookCode.SelectAll();
        //}
        public void SetMember(Member member)
        {
            m_member = member;
            textBoxMemberCode.Text = member.Code;
            textBoxMemberName.Text = member.Name;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            FormFindMember form = new FormFindMember(this);
            form.ShowDialog();
        }

        private void buttonAddBook_Click(object sender, EventArgs e)
        {
            FormBookBorrowAddBook frm = new FormBookBorrowAddBook(this);
            frm.ShowDialog();
        }


        public void AddBook(Book book)
        {
            ListViewItem itm = listView.Items.Add(book.Code);
            itm.SubItems.Add(book.Name);
            itm.SubItems.Add(book.Tag.ToString());
            itm.Tag = book;
        }

        public bool CheckExistBook(Book book)
        {
            foreach (ListViewItem itm in listView.Items)
            {
                Book bookList = (Book)itm.Tag;
                if (book.Id == bookList.Id)
                    return true;
            }
            return false;
        }

        private void buttonREmoveBook_Click(object sender, EventArgs e)
        {
            if (listView.SelectedItem != null)
                listView.Items.Remove(listView.SelectedItem);
        }

        private void textBoxMemberCode_EnterKeyDown(object objSender, KeyEventArgs objArgs)
        {
            IList memberList = m_MemberService.GetMemeberByLike(textBoxMemberCode.Text);
            if (memberList.Count == 1)
                SetMember(memberList[0] as Member);
        }
    }
}